import re, urllib2, time
from google.appengine.ext import webapp

class GeoHashing(webapp.RequestHandler):
    xkcd_url = 'http://wiki.xkcd.com/geohashing/'
    geohash = {}
    def get_coord(self, date):
        if date in self.geohash:
            return self.geohash[date]
        try:
            xkcd_page = urllib2.urlopen(self.xkcd_url+date)
        except:
            return
        if not xkcd_page: return
        for line in xkcd_page:
            found = re.search(r'All locations:</b> (\.\d+), (\.\d+)', line)
            if found:
                coord = (found.group(1), found.group(2))
                self.geohash[date] = coord
                return coord
            elif re.search(r'East of -30', line):
                found = re.search(r':</b> (\.\d+), (\.\d+).*? (\.\d+), (\.\d+)', line)
                if found:
                    coord = (found.group(1), found.group(2), found.group(3), found.group(4))
                    self.geohash[date] = coord
                    return coord
                else:
                    return(line,)
        return

    def get(self):
        params = self.request.params
        if 'date' in params and re.search(r'\d{4}-\d\d-\d\d', params['date']):
            date = params['date']
        else:
            date = time.strftime('%Y-%m-%d')
        coord = self.get_coord(date)

        try:
            lat = int(re.findall('([+-]?\d{1,2})', params['lat'])[0])
        except:
            lat = 40
        try:
            long = int(re.findall('([+-]?\d{1,3})', params['long'])[0])
        except:
            long = -75
        try:
            zoom = re.findall('(\d{1,2})', params['zoom'])[0]
        except:
            zoom = '10'
        if coord and len(coord) > 2:
            if long <= 30:
                coord = coord[0:2]
            else:
                coord = coord[2:4]

        if 'q' in params and params['q'] == 'xkcd':
            if coord:
                self.response.out.write('[%s]' % ', '.join(coord))
            else:
                self.response.out.write('')
            return

        if not coord or len(coord) < 2:
            rest_url = 'geohashing?date=%s&lat=%s&long=%s&zoom=%s' %(date, lat, long, zoom)
            html = '''<div align="center">Unable to find the coordinate for the date specificied.
Please click the link below, modify the date in the URL and try again:<br><div align="center"><a href="%s">%s</a></div>
''' %(rest_url, rest_url)
            self.response.out.write(html)
            return

        html = '''
<html>
<head>
<script>
function get_map(){
    var lat = document.getElementById('lat').value;
    var long = document.getElementById('long').value;
    var zoom = document.getElementById('zoom').value
    var ll = lat + "%s" + ',' + long + "%s";
    var map_url = 'http://maps.google.com/maps?q='+ll+'&ll='+ll+'&t=h&z='+zoom+'&lci=bike&output=embed';
    document.getElementById("if0").setAttribute("src", map_url);
    var a_url = document.getElementById("url");
    var rest_url = 'geohashing?date=%s&lat='+lat+'&long='+long+'&zoom='+zoom;
    a_url.setAttribute("href", rest_url);
    a_url.innerHTML = rest_url;
}
</script>
</head>''' %(coord[0], coord[1], date)
        xkcd = '<a href="%s">%s</a>' %(self.xkcd_url + date, date)
        html += '''
<body onload="get_map()">
<table>
<tr valign="top"><td> <img src="http://isomerica.net/~xkcd/geohashing_logo.png" alt="geohashing"></img></td><td>
%s
Latitude: <input id="lat" type="text" value="%d" size="2" onchange="get_map()"></input>%s
Longitude: <input id="long" type="text" value="%d" size="4" onchange="get_map()"></input>%s
Zoom: <input id="zoom" type="text" value="%s" size="2" onchange="get_map()"></input>
<br>
<iframe id="if0" width="1000" height="700" frameborder="0" scrolling="no" marginheight="0" marginwidth="0">
</iframe>
<br>
<a id="url"></a>
</td></tr></table>
</body>
</html>
''' %(xkcd, lat, coord[0], long, coord[1], zoom)
        self.response.out.write(html)
